package com.yueyang.sojourn.server.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.policy.AlwaysRetryPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;

/**
 * @author yemingxing
 * @summary
 * @Copyright (c) 2020, Ke Group All Rights Reserved.
 * @since 2020-04-05 17:50
 */
@Configuration
@EnableRetry(proxyTargetClass = true)
public class RetryConfig {

    public final static String SIMPLE_RETRY = "simpleRetryTemplate";

    public final static String ALWAYS_RETRY = "alwaysRetryTemplate";

    @Bean(name = SIMPLE_RETRY)
    public RetryTemplate retryTemplate() {
        RetryTemplate retryTemplate = new RetryTemplate();
        retryTemplate.setThrowLastExceptionOnExhausted(true);

        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
        retryPolicy.setMaxAttempts(3);
        retryTemplate.setRetryPolicy(retryPolicy);

        ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
        backOffPolicy.setInitialInterval(200L);
        backOffPolicy.setMultiplier(2);
        retryTemplate.setBackOffPolicy(backOffPolicy);
        return retryTemplate;
    }

    @Bean(name = ALWAYS_RETRY)
    public RetryTemplate alwaysRetryTemplate() {
        RetryTemplate retryTemplate = new RetryTemplate();
        retryTemplate.setThrowLastExceptionOnExhausted(true);

        AlwaysRetryPolicy retryPolicy = new AlwaysRetryPolicy();
        retryTemplate.setRetryPolicy(retryPolicy);
        return retryTemplate;
    }
}
